import axios from "axios";
import {Toast} from "vant";
import {getItem, removeItem} from "@/plugins";
const token = getItem('access_key')
const api = axios.create({
    baseURL: process.env.VUE_APP_API_ROOT,
    withCredentials: false, //cookie 设置
    maxRedirects: 5,
    timeout: 8000,
})

api.interceptors.request.use(
    config=>{
        if (token){
            config.headers['like-admin']=token
            config.headers['lang-admin']=getItem('lang') ? getItem('lang').value :'en'
        }else{
            config.headers['lang-admin']=getItem('lang') ? getItem('lang').value :'en'
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

api.interceptors.response.use(
    response=>{
        if (response.data.code === 200 || response.data.code === 1){
            return response.data
        }else if (response.data.code === 331){
            removeItem('lang')
            removeItem('access_key')
            setTimeout(()=>{
                location.reload()
            },600)
        }else if (response.data.code === 555){
            const url = new URL(location.href);
            const siteURL = `${url.protocol}//${url.host}/50x.html`;
            if (process.env.VUE_APP_API_ROOT ){

            }else{
                location.href=siteURL
            }
        }else if (response.data.code  === 500){
            if (window.navigator && navigator.onLine === true) {
                // Toast({
                //     duration: 3000, // 持续展示 toast
                //     message: response.data.msg ? response.data.msg : setting.public.system[lang],
                // });

            } else {}

            return Promise.reject(response.data)
        }else{
            if (window.navigator && navigator.onLine === true) {
                Toast.fail(response.data.msg)
            } else {
                return Promise.reject(response.data)
            }
        }
    },
    error => {
        return Promise.reject(error)
    }
)

export  default api
